package com.itheima.schedule;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

public class HPF {
    public static void main(String[] args) throws InterruptedException {
        //有序Map，将服务优先级作为key排序
        final TreeMap<Integer, Task> treeMap = new TreeMap();


        //向队列中放入5个任务
        for (int i = 0; i < 5; i++) {
            System.out.println("add task:" + i);
            int servTime = new Random().nextInt(1000);
            //注意放入的key，是优先级，这里用i标识
            treeMap.put(i, new Task("task" + i, servTime,i));
        }

        //服务线程，任务由该线程获取和执行
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        //有序Map中，优先级最高的，在底部部，那么自然就会优先被取出
                        Map.Entry<Integer, Task> entry = treeMap.pollLastEntry();
                        if (entry == null) {
                            Thread.currentThread().sleep(100);
                        } else {
                            entry.getValue().execute();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
